package com.chj.zhongji.class03;

import java.util.ArrayList;
import java.util.List;

import org.junit.Test;

// https://leetcode-cn.com/problems/spiral-matrix/
public class Code02_PrintMatrix {
	public List<Integer> printMatrix(int[][] matrix) {
		List<Integer> res = new ArrayList<>();
		if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
			return res;
		}

		// (tR,tC) 1 2 3 4
		// 5 6 7 8
		// 9 10 11 12
		// 13 14 15 16 (dR,dC)
		int tR = 0;
		int tC = 0;
		int dR = matrix.length - 1;
		int dC = matrix[0].length - 1;
		while (tR <= dR && tC <= dC) {
			// 先打印外圈(1、2、3 4、8、12 16、15、14 13、9、5),
			// 再打印内圈(6 7 11 10)
			printMatrix(res, matrix, tR++, tC++, dR--, dC--);
		}

		return res;
	}

	public void printMatrix(List<Integer> res, int[][] matrix, int tR, int tC, int dR, int dC) {
		// 对边界处理
		if (tC == dC) {
			for (int i = tR; i <= dR; i++) {
//				System.out.print(matrix[i][tC] + " ");
				res.add(matrix[i][tC]);
			}
		} else if (tR == dR) {
			for (int i = tC; i <= dC; i++) {
//				System.out.print(matrix[tR][i] + " ");
				res.add(matrix[tR][i]);
			}
		} else {
			int curR = tR;
			int curC = tC;
			while (curC != dC) {
//				System.out.print(matrix[tR][curC++] + " ");
				res.add(matrix[tR][curC++]);
			}

			while (curR != dR) {
//				System.out.print(matrix[curR++][dC] + " ");
				res.add(matrix[curR++][dC]);
			}

			while (curC != tC) {
//				System.out.print(matrix[dR][curC--] + " ");
				res.add(matrix[dR][curC--]);
			}

			while (curR != tR) {
//				System.out.print(matrix[curR--][tR] + " ");
				res.add(matrix[curR--][tR]);
			}
		}
	}

	@Test
	public void test() {
		int[][] matrix = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } };
		printMatrix(matrix);
	}

}
